<?php

declare (strict_types=1);


namespace App\Models\GameDB\Pet;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UserSeasonRecord extends Model
{
    protected $connection = 'mysql_game';
    protected $table = 'lottery_pet_user_season_record';
    protected $guarded = [];

    public function one(array $filters, $orderBy = "id", $sort = 'desc', bool $lock = false)
    {
        $query = self::query()->where($filters);
        $query->orderBy($orderBy, $sort);
        if ($lock) {
            $query->lockForUpdate();
        }

        return $query->first();
    }

    public function addUserPropCount($filters, $propsCount)
    {
        return self::query()->where($filters)->update(['prop' => DB::raw("browse_count+1")]);

    }

    public function list(array $filters, $fields = ['*'], $orderBy = "id", $sort = "desc", $limit = 10, $offset = 0)
    {
        $query = self::query()->where($filters)->select($fields)->orderBy($orderBy, $sort);
        if (!empty($offset)) {
            $query->offset($offset);
        }
        if (!empty($limit)) {
            $query->limit($limit);
        }

        return $query->get();

    }

    public function updateData(array $filters, array $data)
    {
        return self::query()->where($filters)->update($data);
    }

//    public function listWithUser(array $filters, $fields = ['*'], $orderBy = "id", $sort = "desc", $limit = 10)
//    {
//        return self::query()->join('ln_user_data ud', $this->table.'.user_id', 'ud.user_id')->where($filters)->select($fields)->orderBy($orderBy, $sort)->limit($limit)->get();
//    }


    // 批量增加礼物数量（抽完补奖池, 额外设置总数）
    public function batchUpdatePresentProps($season, $data)
    {
        $userIds       = array_column($data, 'user_id');
        $userIdsString = implode(',', $userIds);

        $table = $this->getTable();
        $sql   = "update {$table} set ";
        // 增加数量
        $sql .= "`present_prop_count` = case `user_id`";
        foreach ($data as $value) {
            $sql .= "when {$value['user_id']} then {$value['present_prop_count']} ";
        }
        $sql .= "else `present_prop_count` end";

        // 条件
        $sql .= " where season = '{$season}' and user_id in ($userIdsString)";

        return DB::connection('mysql_game')->update($sql);
    }
}